<template>
  <div class="pwd-box">
    <el-form
      :model="data.form"
      label-width="120px"
      label-position="left"
      ref="ruleFormRef"
      :rules="data.rules"
    >
      <el-form-item prop="origPwd" label="原密码">
        <el-input
          type="password"
          v-model="data.form.origPwd"
          placeholder="请输入原密码"
        />
      </el-form-item>
      <el-form-item prop="newPwd" label="新密码">
        <el-input
          type="password"
          v-model="data.form.newPwd"
          placeholder="请输入新秘密"
        />
      </el-form-item>
      <el-form-item prop="newPwd2" label="新密码">
        <el-input
          type="password"
          v-model="data.form.newPwd2"
          placeholder="请再次输入新秘密"
        />
      </el-form-item>
      <p><el-button type="primary" @click="save()">保存修改</el-button></p>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, computed, ref, reactive } from 'vue'
import { useStore } from '@/pinia/index'
import { useRouter } from 'vue-router'
import { updatePasswordApi } from '@/api/mgmtUser' //api/后面不能大写Mgmt
import { ElMessage } from 'element-plus'
const pinia = useStore()
const router = useRouter()
const data = reactive({
  form: {
    origPwd: '',
    newPwd: '',
    newPwd2: '',
  },
  rules: {
    origPwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        required: true,
        pattern: /^[a-zA-Z0-9]{4,16}$/,
        message: '4到16位(字母，数字)',
        trigger: 'blur',
      },
    ],
    newPwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        required: true,
        pattern: /^[a-zA-Z0-9]{4,16}$/,
        message: '4到16位(字母，数字)',
        trigger: 'blur',
      },
    ],
    newPwd2: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        required: true,
        pattern: /^[a-zA-Z0-9]{4,16}$/,
        message: '4到16位(字母，数字)',
        trigger: 'blur',
      },
    ],
  },
})
const ruleFormRef = ref(null)
const save = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (data.form.origPwd !== pinia.userInfo.pwd) {
        ElMessage({ message: '原密码不正确', type: 'error' })
        return
      }
      if (data.form.newPwd !== data.form.newPwd2) {
        ElMessage({ message: '2次密码不一样', type: 'error' })
        return
      }
      const param = { id: pinia.userInfo.id, pwd: data.form.newPwd }
      const res = await updatePasswordApi(param)
      if (res.data) {
        ElMessage({ message: '修改成功', type: 'success' })
        //退出登录
        pinia.updataUser('', '')
        router.push({ path: '/login' })
      }
    }
  })
}
onMounted(() => {})
</script>
<style scoped lang='scss'>
.pwd-box {
  width: 500px;
  margin: 20px;
}
</style>
